import 'package:flutter/material.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 自定义Tab指示器，支持固定高宽
class CustomTabIndicator extends Decoration {
  /// 指示器宽度
  final double width;
  
  /// 指示器高度
  final double height;
  
  /// 指示器颜色
  final Color color;
  
  /// 指示器圆角
  final double borderRadius;
  
  /// 指示器内边距
  final EdgeInsetsGeometry indicatorPadding;
  
  /// 指示器是否居中
  final bool isCentered;

  const CustomTabIndicator({
    this.width = 60,
    this.height = 4,
    this.color = AppColor.primary,
    this.borderRadius = 2,
    this.indicatorPadding = EdgeInsets.zero,
    this.isCentered = true,
  });

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return CustomTabIndicatorPainter(
      this,
      onChanged,
    );
  }

  @override
  EdgeInsetsGeometry get padding => indicatorPadding;
}

/// 自定义Tab指示器绘制器
class CustomTabIndicatorPainter extends BoxPainter {
  final CustomTabIndicator decoration;

  CustomTabIndicatorPainter(
    this.decoration,
    VoidCallback? onChanged,
  ) : super(onChanged);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final Rect rect = offset & configuration.size!;
    
    // 计算指示器的实际位置和尺寸
    double indicatorWidth = decoration.width.w;
    double indicatorHeight = decoration.height.w;
    
    // 如果指示器宽度大于可用宽度，则使用可用宽度
    if (indicatorWidth > rect.width) {
      indicatorWidth = rect.width;
    }
    
    // 计算指示器的水平位置
    double left;
    if (decoration.isCentered) {
      left = rect.left + (rect.width - indicatorWidth) / 2;
    } else {
      left = rect.left;
    }
    
    // 计算指示器的垂直位置（底部对齐）
    double top = rect.bottom - indicatorHeight - decoration.indicatorPadding.vertical;
    
    // 创建指示器矩形
    final Rect indicatorRect = Rect.fromLTWH(
      left,
      top,
      indicatorWidth,
      indicatorHeight,
    );
    
    // 绘制指示器
    final Paint paint = Paint()
      ..color = decoration.color
      ..style = PaintingStyle.fill;
    
    // 绘制圆角矩形
    final RRect roundedRect = RRect.fromRectAndRadius(
      indicatorRect,
      Radius.circular(decoration.borderRadius.w),
    );
    
    canvas.drawRRect(roundedRect, paint);
  }
}
